<?php

/*
 * @requires inc/005.autoload-function.php 0.3.1
 * @version 0.1
 * @package 0.3.1
*/

class xStyler {

    private static $db_used = false;

    static function init() {
    }

    private static function skin_dir($skin = false) {
	if (! $skin)
	    $skin = X::cfg('skin:default');
	return 'usr/skins/' . $skin;
    }

    public static function locate($file) {
	X::notice ( 'Styler searching for file ' . $file);
	$ext = xFsTools::fileext($file);

	$so = X::cfg('skin:skin_order');
	$uo = self::get_user_skins ();
	$so = array_merge ( $uo, $so );
	for($x = 0; $x < count ( $so ); $x ++) {
	    $dir = self::skin_dir ( $so [$x] );
	    $test = $dir . '/' . $ext . '/' . $file;
	    echo "$test<br/>\r\n";
	    if (file_exists ( $test )) {
		X::notice ( "File `$file` located as `$test`", 'styler.log' );
		return $test;
	    }
	}

	X::warning ( 'Styler was unable to locate file <' . $file . '>!', 'styler.log' );
	return '';
    }

    private static function build_skin_css($skin = NULL) {
	if ($skin === NULL)
	    $skin = X::cfg('skin:default');
	$ret = "\r\n\r\n/* =================================================================\r\n" . "   CSS code of skin <$skin>\r\n" . "   ================================================================= */\r\n";
	$dir = self::skin_dir ( $skin ) . '/css';
	if ($incdir = opendir ( $dir )) {
	    while ( false !== ($file = readdir ( $incdir )) ) {
		if (is_file ( $dir . '/' . $file )) {
		    $ret .= "\r\n /* ---------------------------------------\r\n$file contents\r\n*/\r\n" . file_get_contents ( $dir . '/' . $file );
		}
	    }
	}
	return $ret;
    }

    public static function build_css() {
	$so = X::cfg('skin:skin_order');
	$uo = self::get_user_skins ();
	$so = array_merge ( $uo, $so );
	$ret = '';
	for($x = count ( $so ); $x > 0; $x --) {
	    $ret .= self::build_skin_css ( $so [$x - 1] );
	}

	return $ret;
    }

    private static function get_user_skins() {
	$skins = array ();
	if (self::$db_used)
	    return $skins;
	X::notice ( 'loading user skins...', 'styler.log' );
	try {
	    $res = RQL::exec( 'group / $skin', 'skin.weight ASC' );
	} catch ( Exception $e ) {
	    self::$db_used = true;
	    X::warning ( 'FAILED', 'styler.log' );
	    return $skins;
	}

	if ($res) {
	    while ( $line = $res->current () ) {
		$skins [] = $line->skin->name;
		$res->next ();
	    }
	    X::notice ( 'Done, loaded ' . count ( $skins ) . ' skins', 'styler.log' );
	} else X::notice('Loading failed: no result', 'styler.log');
	return $skins;
    }
}

?>